package com.bang.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: Bang
 * @Date: 2019/10/4 20:02
 * @Description:
 */
@Slf4j
public class CyclicBarrierExample3 {

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
        @Override
        public void run() {
            log.error("CALLBACK IS RUNNING");
        }
    });

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int threadNum = i;
            Thread.sleep(1000);
            executorService.execute(() -> {
                race(threadNum);
            });
        }
        executorService.shutdown();
    }

    private static void race(int threadNum) {
        try {
            Thread.sleep(1000);
            log.error("ready {}", threadNum);
            cyclicBarrier.await();
        }  catch (Exception e) {
            log.error("e:{}", e.getMessage());
        }
        log.error("continue {}", threadNum);

    }
}
